package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import util.BinarySort;
import util.ParameterCheck;
import util.PinYin;

import model.Item;

import common.Constant;
import common.StartupServlet;

public class ItemDao extends RpDao {
	public int CreateItem(Item item) {
		int n = 0;
		Connection conn=this.getConn();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			// insertItem = "insert into item(name,name_py,name_py2,tags,img) values(?,?,?,?,?)",
			ps = conn.prepareStatement(SqlString.insertItem,
					Statement.RETURN_GENERATED_KEYS);
			int i = 1;
			ps.setString(i++, item.getName());
			ps.setString(i++, item.getName_py());
			ps.setString(i++, item.getName_py2());
			ps.setString(i++, item.getTags());
			ps.setString(i++, item.getImg().replace(Constant.imgurl, ""));
			n = ps.executeUpdate();
			if (1 == n) {
				rs = ps.getGeneratedKeys();
				rs.next();
				n = rs.getInt(1);// 成功则返回 itemid
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			n = -1;
		} finally {
			this.closeDao(conn, ps, rs);
		}
		return n;
	}

	/**
	 * 
	 * @param itemid
	 * @return
	 */
	public int updateHot(int itemid, int hot) {
		int res = 0;
		Connection conn=this.getConn();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = conn.prepareStatement(SqlString.updateItemhot);

			pstmt.setInt(1, hot);
			pstmt.setInt(2, itemid);
			res = pstmt.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			this.closeDao(conn,pstmt, rs);
		}

		return res;

	}

	public int updateCommentCount(int itemid, int hot) {
		int res = 0;
		Connection conn=this.getConn();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
//			updateItemComment_count = "update item set comment_count=comment_count+? where id=? ",
			pstmt = conn.prepareStatement(SqlString.updateItemComment_count);

			pstmt.setInt(1, hot);
			pstmt.setInt(2, itemid);
			res = pstmt.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			this.closeDao(conn,pstmt, rs);
		}

		return res;

	}
	
	public Item query(int itemid) {
		Item it = null;
		Connection conn=this.getConn();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = conn.prepareStatement(SqlString.selectItemById);
			pstmt.setInt(1, itemid);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				it = new Item();
				it.setId(rs.getInt("id"));
				it.setBirth(rs.getString("birth"));
				it.setCtime(rs.getString("ctime"));
				it.setGender(rs.getBoolean("gender"));
				it.setHot(rs.getInt("hot"));
				it.setName(rs.getString("name"));
				it.setName_py(rs.getString("name_py"));
				it.setImg(rs.getString("img"));
				it.setTags(rs.getString("tags"));
				it.setComment_count(rs.getInt("comment_count"));
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} 
		finally{
			this.closeDao(conn, pstmt, rs);
		}
		return it;
	}

	public List<Item> findItems(List<String> tags,int index,List<Integer>  totalPage) {
		List<Item> items = new ArrayList<Item>();
		Connection conn=this.getConn();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		//先检查之前是否搜索过该关键词
		final TmpSearchDao tmpsearch=new TmpSearchDao();
		
		items=tmpsearch.getSearchCache(tags, index, totalPage);
		
		if (items.size()>0 ) //如果缓存中有结果 则返回缓存中的结果
			return items;
			
		//如果之前没有搜索过，那么开始一次新的搜索，并将此次的搜索结果异步缓存
		
		int itemcount=0;//搜索返回的item数  达到系统限制的最大数量时就返回 不再继续遍历
		try{
			for (String tag : tags) {
			if (tag.length() > 1 && tag.length() < 20) {
				
//					selectItemByName_py2 = "select * from item where name_py2 like ", 
					String str=PinYin.getPinyin2(PinYin.getPinyin(tag));
					String sql=SqlString.selectItemByName_py2+"\"%"+str+"%\"";
					System.out.println(sql);
					try {
					rs=conn.createStatement().executeQuery(sql);
					while (rs.next()) {
						System.out.println("xxxx");
						Item it = new Item();
						it.setId(rs.getInt("id"));
						it.setBirth(rs.getString("birth"));
						it.setCtime(rs.getString("ctime"));
						it.setGender(rs.getBoolean("gender"));
						it.setHot(rs.getInt("hot"));
						it.setName(rs.getString("name"));
						it.setName_py(rs.getString("name_py"));
						it.setName_py2(rs.getString("name_py2"));
						it.setImg(ParameterCheck.stringDefault(rs.getString("img")));
						it.setTags(rs.getString("tags"));
						it.setHot(rs.getInt("hot"));
						System.out.println("1111");
						it.setComment_count(rs.getInt("comment_count"));
						System.out.println("2222");
						it.setMatchdegree(Constant.baseMatchDegree+it.getHot()*Constant.VoteWeight+it.getComment_count()*Constant.CommentWeight);
						System.out.println("3333");
						it.setMatchedTags("");
						if(items.contains(it))
							continue;
						BinarySort.insertItem(items, it, tags);
//						System.out.println("name:"+it.getName());
						if(itemcount++>Constant.MaxSearchCount)
							break;
					}
					if(itemcount++>Constant.MaxSearchCount)
						break;
					}catch (Exception e) {
						// TODO: handle exception
					}

			}
		}
		}
		 finally {
				this.closeDao(conn,pstmt, rs);
			};
		final List<Item> itemlist = items;
		final String searchWord=tags.toString();
		new Thread(){
			public void run(){
				tmpsearch.saveSearchResult(searchWord,itemlist);
			}
		}.start();
		
		int begin,end=0;
		 begin=index*Constant.PageSize;
		 end=(index+1)*Constant.PageSize;
		 if (end>items.size())
			 end=items.size();
		 if (begin>items.size())
			 begin=0;
		 totalPage.add((items.size()-1)/Constant.PageSize );
		return items.subList(begin,end);
	}

	public static void main(String[] args) {

		new StartupServlet();
		ItemDao id = new ItemDao();
		// System.out.println(id.updateHot(2, 5));
		Item i = id.query(1);
		System.out.println(i.getImg());
		System.out.println(i.getBirth());
		System.out
				.println(i.getName() + "," + i.getTags() + "," + i.getCtime());
	}
}
